<template>
  <TableBody>
    <template #header>
      <TableHeader ref="tableHeaderRef" :show-filter="false" :title="stage?.name">
        <template #top-right>
<!--          {{taskNum}}-->
          <n-tag type="error"> {{stageMenuMap.get("0")}} : {{ taskNum.get("0")?taskNum.get("0").length:0}} </n-tag>
          <n-tag type="success"> {{stageMenuMap.get("1")}} : {{taskNum.get("1")?taskNum.get("1").length:0}} </n-tag>
          <n-tag type="default"> {{stageMenuMap.get("3")}} : {{taskNum.get("3")?taskNum.get("3").length:0}} </n-tag>
          <AddButton @add="onAddItem" />
        </template>
      </TableHeader>
    </template>
    <template #default>
      <n-layout
          has-sider
          style="height: 500px"
      >
        <n-layout-sider
            bordered
            show-trigger
            collapse-mode="width"
            :collapsed-width="64"
            :width="150"
            :native-scrollbar="false"
            style="max-height: 320px"
        >
          <n-menu
              v-model:value="getInfo.showState"
              :collapsed-width="64"
              :collapsed-icon-size="22"
              :options="satgeMenuOptions"
          />
        </n-layout-sider>
        <n-layout-content content-style="padding: 24px;">
<!--          {{table.dataList}}-->
          <n-data-table
              :loading="table.tableLoading.value"
              :data="table.dataList.value as Array<object>"
              :row-key="rowKey"
              :columns="tableColumns"
              :scroll-x="500"
              :style="{ height: `${table.tableHeight.value*2}px` }"
              :flex-height="true"
              :row-props="rowProps"
              :pagination="false"
              :bordered="false"
              :id="'stageModeItemDragTable'+props.type"
              handle="#handle-drag"
          />
          <n-dropdown
              placement="bottom-start"
              trigger="manual"
              :x="xRef"
              :y="yRef"
              :options="options"
              :show="showDropdownRef"
              :on-clickoutside="onClickoutside"
              @select="handleSelect"
          />
        </n-layout-content>
      </n-layout>

      <!--          @update:checked-row-keys="onRowCheck"-->

    </template>
  </TableBody>
  <TaskEditDrawer v-model="formData"></TaskEditDrawer>
<!--  <ModalDialog ref="modalDialogRef" @confirm="onDataFormConfirm" contentHeight="120vh">-->
<!--    <template #content>-->
<!--      <DataForm ref="dataFormRef" :options="formItems" :form-config="formConfig"/>-->
<!--    </template>-->
<!--  </ModalDialog>-->
</template>
<script lang="ts">
import {TableActionModel, usePagination, useRenderAction, useRowKey, useTable, useTableColumn} from "@/hooks/table";
import {
  DataTableColumn,
  FormProps,
  NAvatar,
  NDrawer,
  NInput, NText,
  NTime,
  SelectOption,
  useDialog,
  useMessage
} from "naive-ui";
import {post, Response} from "@/api/http";
import {
  addLifeModeItems,
  addStage,
  changeGoalState,
  changeLifeModeItemsOrder,
  changeStageOrder,
  changeStageState,
  changeTaskOrder,
  changeTaskState,
  deleteStage,
  deleteTask, finishTask,
  getFieldSelect,
  getGoalSelect,
  getStageById,
  getStagesList,
  getTableList,
  getTasksList
} from "@/api/url";
import {defineComponent, h, onMounted, ref, watch, defineProps, nextTick, reactive, onBeforeMount, computed} from "vue";
import {renderSelect, renderTag, renderTimePicker, renderTreeSelect,renderIcon} from "@/hooks/form";
import GoalTree from "@/views/field/goal/GoalTree.vue";
import useUserStore from "@/store/modules/user";
import UseSurfaceSettingStore from "@/store/modules/surfaceSetting";
import { DataFormType, ModalDialogType, FormItem } from '@/types/components'
import {TreeSelectOption} from "naive-ui/lib/tree-select/src/interface";
import { Book } from "@vicons/ionicons5";
import {UseConstsStore} from "@/store/modules/consts";
import pinia from "@/store/pinia";
import {changeTimeUnit, obj2Map} from "@/utils";
import Sortable from "sortablejs";
import {TimeMentionModal,TaskData,StageData} from "@/views/model/model";
import TaskEditDrawer from "@/views/task/TaskEditDrawer.vue";
import MyTime from "@/views/task/time/MyTime.vue";
import TaskMoveModal from "@/views/task/TaskMoveModal.vue";


export default defineComponent({
  name: 'TaskList',
  methods: {obj2Map},
  components: {TaskMoveModal, MyTime, TaskEditDrawer, NDrawer},
  props:{
    type:Number
  },
  setup(props) {
    const key = ref<number>(new Date().getTime())
    const table = useTable()
    const rowKey = useRowKey('id')
    const naiveDialog = useDialog()
    const message = useMessage()
    const userStore = useUserStore()
    const useSurfaceSetting = UseSurfaceSettingStore()
    const useConsts = UseConstsStore()
    // const pagination = usePagination(doRefresh)
    const checkedRowKeys = [] as Array<any>
    const surfaceSetting = useSurfaceSetting.getSurfaceSetting();
    const satgeMenuOptions = computed(()=>{
      return useConsts.getStateList().map(u=>{return {...u,icon:renderIcon(Book)}})
    })
    const stageMenuMap = computed(()=>{
      return obj2Map(useConsts.getConsts().stateMap)
    })
    const taskType = 1
    const tableColumns = useTableColumn(
        [
          // table.selectionColumn,
          // table.indexColumn,
          {
            title: 'id',
            key: 'id',
          },
          {
            title: '任务名',
            key: 'name',
          },
          {
            title: '阶段名',
            key: 'stageName',
          },
          {
            title: '领域名',
            key: 'fieldName',
          },
          {
            title: '目标名',
            key: 'goalName',
          },
          {
            title: '提醒时间',
            key: 'mentionTime',
            render: (rowData) => {
              return h(MyTime,{
                time:rowData.mentionTime,
                type:"datetime"
              },{})
            }
          },
          {
            title: '截止时间',
            key: 'timeMentionModal.deadLine',
            render: (rowData:any) => {
              return h(MyTime,{
                time:rowData.timeMentionModal.deadLine,
                type:"datetime"
              },{})
            }
          },
          {
            title: '描述',
            key: 'desc',
            width: 100,
            ellipsis: {
              tooltip: true,
            },
          },
          {
            title: '完成率',
            key: 'finishRatio',
          },
          {
            title: '所花时间',
            key: 'takeTime',
            render: (rowData:any) => {
              return h(NText,{},{
                default: () => changeTimeUnit(rowData.takeTime),
              })
            }
          },
          {
            title: '操作',
            key: 'actions',
            render: (rowData) => {
              let type = 'default'
              if(rowData.id === useSurfaceSetting.getSurfaceSetting().onLifeModeId)
                type = 'error';
              return useRenderAction([
                {
                  label: '上下移动',
                  type:type,
                  // onClick: onUpdateItem.bind(null, rowData),
                  id: "handle-drag"
                }
              ] as TableActionModel[])
            },
          },
        ],
        {
          align: 'center',
        } as DataTableColumn
    )
    const getInfo = reactive<{type:number|undefined,id:number|null,showState:string}>({
      type:props.type,
      id:surfaceSetting.showStageId[0],
      showState: JSON.stringify( props.type === taskType?surfaceSetting.showTaskTypeState:surfaceSetting.showClockTypeState),
      // data:StageData.getNewStageData()
    })
    watch(getInfo,()=>{
      const setting = useSurfaceSetting.getSurfaceSetting()
      if(getInfo.type === taskType){
        setting.showTaskTypeState = parseInt(getInfo.showState)
      }else {
        setting.showClockTypeState = parseInt(getInfo.showState)
      }
      // console.log(getInfo)
      // doRefresh()
      key.value = Date.now()
    })
    watch(useSurfaceSetting.getSurfaceSetting(),async ()=>{
      const setting = useSurfaceSetting.getSurfaceSetting()
      if( getInfo.id !== setting.showStageId[0]){
        getInfo.id = surfaceSetting.showStageId[0]
        // await getInfoFromBack()
        // await doRefresh()
        key.value = Date.now()
      }
    })

    // 加载数据
    const stage = ref<StageData>(StageData.getNewStageData())
    const taskNum = computed(()=>{
      if(stage.value.tasks && Object.keys(stage.value.tasks).length>0){
        const tasksType = obj2Map(stage.value.tasks);
        if(tasksType.size>0 && tasksType.get(JSON.stringify(getInfo.type))){
          const tasks = obj2Map(tasksType.get(JSON.stringify(getInfo.type)))
          return tasks;
        }
      }
      return new Map();
    })
    const getStageInfo = async ()=>{
      try {
        const res: Response = await post({
          url: getStageById,
          data: {id:getInfo.id},
          token:userStore.getToken()
        });
        if(res.data.data) stage.value = res.data.data
        console.log(stage.value.tasks,"+++++++++++++++++++++++")
      }catch(e) {
        message.error((e as Error).message)
      }finally {

      }
    }
    async function doRefresh() {
      // await getInfoFromBack()
      // 获取阶段的信息
      const info = getInfo
      // console.log("++++++++++++++++",info.data.tasks)
      table.tableLoading.value = true
      // console.log({taskIds:taskIds,finishStageId:finishStageId})
      try {
        const res: Response = await post({
          url: getTasksList,
          data: {stageId:getInfo.id,state:getInfo.showState,type:getInfo.type},
          token:userStore.getToken()
        });
        // console.log(data)
        // console.log(res.data.data)
        await table.handleSuccess({data:res.data.data})
        // console.log(table.dataList)
        table.tableLoading.value = false
        getStageInfo()
        setSort()
      }catch(e) {
        message.error((e as Error).message)
      }finally {

      }
      if(!table.dataList.value){
        table.dataList.value = []
        table.tableLoading.value = false
      }
      // console.log(table.dataList.value)
    }
    onMounted(doRefresh)
    // 添加/编辑框
    const formData = reactive({
      show:false,
      key:Date.now(),
      taskPanel:false,
      edit:true,
      data:{...TaskData.getNewTaskData(parseInt(getInfo.showState),getInfo.type,getInfo.id),fieldId:stage.value.fieldId,goalId:stage.value.goalId}
    })
    watch(formData,async ()=>{
      // console.log(formData.key, key.value)
      if(formData.key !== key.value){
        // await getInfoFromBack()
        // await doRefresh()
        key.value = Date.now()
      }
    })
    watch(key, async ()=>{
      // console.log(key,"+++++++++++++")
      // await getInfoFromBack()
      await doRefresh()
      formData.key= key.value
    })


    // 删除添加
    function onAddItem() {
      formData.data = {...TaskData.getNewTaskData(parseInt(getInfo.showState),getInfo.type,getInfo.id),fieldId:stage.value.fieldId,goalId:stage.value.goalId}
      formData.show = true
    }
    function onUpdateItem(item: TaskData|null) {
      if(item){
        formData.data = {...item, fieldId:stage.value.fieldId,goalId:stage.value.goalId}
        console.log(formData.data)
        formData.show = true
      }
    }
    function onDeleteItem(item: any) {
      naiveDialog.warning({
        title: '提示',
        content: '确定要删除此数据吗？',
        positiveText: '确定',
        onPositiveClick: async () => {
          table.dataList.value!.splice(table.dataList.value!.indexOf(item), 1)
          try {
            // table.tableLoading.value = true;
            const data: Response = await post({
              url: deleteTask,
              data: item,
              token:userStore.getToken()
            });
            // console.log(data)
            message.success(data.msg)
          }catch(e) {
            message.error((e as Error).message)
          }finally {
            // table.tableLoading.value = false;
          }
        },
      })
    }
    const finishTaskFunc = async (fial:boolean, taskId:number|null|undefined,ddl:number,mentionTime:number) => {
      try {
        const data : Response = await post({
          url: finishTask,
          data: {id:taskId, fial:fial,mentionTime:mentionTime,deadLine:ddl},
          token:userStore.getToken()
        });
        // console.log(data)
        message.success(data.msg)
      }catch(e) {
        message.error((e as Error).message)
      }finally {
        key.value = Date.now()
      }
    }
    const changeState = async (params:any) => {
      // table.tableLoading.value = true;
      try {
        const data : Response = await post({
          url: changeTaskState,
          data: params,
          token:userStore.getToken()
        });
        // console.log(oldState,newState)
        message.success(data.msg)
      }catch(e) {
        message.error((e as Error).message)
      }finally {
        key.value = new Date().getTime()
        // table.tableLoading.value = false;
      }
    }

    // 下来菜单
    let chooseRow:TaskData|null = null;
    const options = [
      {
        label: "编辑",
        key: "edit",
      },
      {
        label: "完成任务",
        key: "success",
      },
      {
        label: "任务失败",
        key: "fail",
      },
      {
        label: "开启任务",
        key: "start",
      },
      {
        label: "暂停任务",
        key: "stop",
      },
      {
        label: "结束任务",
        key: "finish",
      },
      // {
      //   label: "移动",
      //   key: "move",
      // },
      {
        label: () => h("span", { style: { color: "red" } }, "删除"),
        key: "delete",
      },
    ];
    const showDropdownRef = ref(false);
    const xRef = ref(0);
    const yRef = ref(0);
    const onClickoutside = () => {
      showDropdownRef.value = false;
    };
    function onFinishGoal(params: TaskData|null, str:string, newState:number){
      if(params){
        naiveDialog.warning({
          title: '提示',
          content: '是否要选择'+str+'该任务:'+params.name+'？',
          positiveText: '确定',
          onPositiveClick:() => {
            changeState({id:params.id, stageId:params.stageId,taskType:getInfo.type,oldState:params.state,newState:newState})
            formData.key = Date.now()
          },
        })
      }
    }

    const handleSelect = async (key: string, node: string) => {
      // console.log(key, node);
      showDropdownRef.value = false;
      if (key == "edit") {
        onUpdateItem(chooseRow)
      }
      if (key == "delete") {
        onDeleteItem(chooseRow)
      }
      if(key == "success"){
        if(chooseRow && chooseRow.type){
          // console.log(new Date(chooseRow.timeMentionModal.deadLine),new Date(chooseRow.timeMentionModal.beginMentionTime))
          chooseRow.timeMentionModal.beginMentionTime = chooseRow.timeMentionModal.deadLine
          const mentionTime = TimeMentionModal.computeMentionTime(chooseRow.timeMentionModal,chooseRow.type)
          const ddl = TimeMentionModal.computeNextClockTime(chooseRow.timeMentionModal,chooseRow.type)
          // console.log(new Date(ddl),new Date(chooseRow.timeMentionModal.deadLine))
          await finishTaskFunc(false,chooseRow.id,ddl,mentionTime)
          if(chooseRow.type === 1) await changeState({id:chooseRow.id, stageId:chooseRow.stageId,taskType:chooseRow.type,oldState:chooseRow.state,newState:3})
        }
      }
      if(key == "fail"){
        if(chooseRow && chooseRow.type){
          chooseRow.timeMentionModal.beginMentionTime = chooseRow.timeMentionModal.deadLine
          const mentionTime = TimeMentionModal.computeMentionTime(chooseRow.timeMentionModal,chooseRow.type)
          const ddl = TimeMentionModal.computeNextClockTime(chooseRow.timeMentionModal,chooseRow.type)
          await finishTaskFunc(true,chooseRow.id,ddl,mentionTime)
          if(chooseRow.type === 1) await changeState({id:chooseRow.id, stageId:chooseRow.stageId,taskType:chooseRow.type,oldState:chooseRow.state,newState:3})
        }
      }
      const str = key==='start'?'开启':key==='stop'?'暂停':'结束';
      if (key == "start") {
        onFinishGoal(chooseRow,str,0)
      }
      if (key == "stop") {
        onFinishGoal(chooseRow,str,1)
      }
      if (key == "finish") {
        onFinishGoal(chooseRow,str,3)
      }
      if (key == "move") {
        // onFinishGoal(chooseRow,str,3)
      }
    };
    const rowProps = (row:TaskData) => {
      return {
        // 双击
        ondblclick: (e: MouseEvent) => {
          e.preventDefault()
          // message.info(JSON.stringify(row, null, 2));
          showDropdownRef.value = true;
          xRef.value = e.clientX;
          yRef.value = e.clientY;
          // console.log('rowProps',row)
          chooseRow = row
        },
        onContextmenu: (e: MouseEvent) => {
          e.preventDefault()
          // message.info(JSON.stringify(row, null, 2));
          showDropdownRef.value = true;
          xRef.value = e.clientX;
          yRef.value = e.clientY;
          // console.log('rowProps',row)
          chooseRow = row
        },
      };
    };

    // 移动
    function setSort() {
      /* 阻止火狐浏览器在  vue-draggable组件时拖动 打开新窗口 */
      document.body.ondrop = function(event) {
        event.preventDefault();
        event.stopPropagation();
      };

      let el = document.querySelector("#stageModeItemDragTable"+props.type+" table tbody");
      // console.log('el',el);
      if(el)
        new Sortable(el as any, {
          handle: "#handle-drag",
          sort: true,
          ghostClass: "sortable-ghost",
          preventOnFilter: false,
          onEnd: async function (/**Event*/ e: any) {
            const list = table.dataList.value?.map(l=>l.id);
            if(list){
              const targetRow = list.splice(e.oldIndex, 1)[0];
              list.splice(e.newIndex, 0, targetRow);
              // console.log(list)
              try {
                const setting = useSurfaceSetting.getSurfaceSetting()
                table.tableLoading.value = true;
                const data : Response = await post({
                  url: changeTaskOrder,
                  data: {ids:list,stageId:getInfo.id,taskType:getInfo.type,state:getInfo.showState},
                  token:userStore.getToken()
                });
                // console.log(data)
                message.success(data.msg)
              }catch(e) {
                message.error((e as Error).message)
              }finally {
                table.tableLoading.value = false;
              }
            }
            // console.log(e)
            // e.preventDefault()
          },
        });
    }
    function onRowCheck(rowKeys: Array<any>) {
      checkedRowKeys.length = 0
      checkedRowKeys.push(...rowKeys)
    }
    return {
      key,stage,stageMenuMap,taskNum,
      formData,
      xRef,yRef,options,handleSelect,onClickoutside,showDropdownRef,
      getInfo,satgeMenuOptions,
      rowProps,
      props,onAddItem,
      table,
      rowKey,checkedRowKeys,onDeleteItem,
      onRowCheck,tableColumns,
      pattern: ref(''),
    }
  },
})

</script>

<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>